/*
MACROS:
LAYER1, LAYER2, LAYER3 = 0 (off), 1 (additive), 2 (blending)
*/

float4x4 g_WorldViewProj;

float2 g_FogParams; // a*x+b
float4 g_FogColor;

float4x2 g_TexTransform0;
texture g_Texture0;
float4 g_Color0;
sampler Sampler0 = sampler_state {
	Texture = g_Texture0; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = LINEAR; AddressU = WRAP; AddressV = WRAP;
};

#if LAYER1 != 0
	float4x2 g_TexTransform1;
	texture g_Texture1;
	float4 g_Color1;
	sampler Sampler1 = sampler_state {
		Texture = g_Texture1; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = LINEAR; AddressU = WRAP; AddressV = WRAP;
	};
#endif
#if LAYER2 != 0
	float4x2 g_TexTransform2;
	texture g_Texture2;
	float4 g_Color2;
	sampler Sampler2 = sampler_state {
		Texture = g_Texture2; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = LINEAR; AddressU = WRAP; AddressV = WRAP;
	};
#endif
#if LAYER3 != 0
	float4x2 g_TexTransform3;
	texture g_Texture3;
	float4 g_Color3;
	sampler Sampler3 = sampler_state {
		Texture = g_Texture3; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = LINEAR; AddressU = WRAP; AddressV = WRAP;
	};
#endif

struct APP_TO_VS
{
	float3 Pos : POSITION;
	float2 Tex : TEXCOORD0;
};

struct VS_TO_PS
{
	float4 Pos : POSITION;
	float2 Tex : TEXCOORD0;
};

void VS(in APP_TO_VS In, out VS_TO_PS Out)
{
	Out.Pos = mul(float4(In.Pos, 1), g_WorldViewProj);
	Out.Tex = In.Tex;
}

void PS(in VS_TO_PS In, out float4 Out : COLOR0)
{
	float2 texCoords = mul(In.Tex, (float2x2)g_TexTransform0) + g_TexTransform0._41_42;
	float4 sample = tex2D(Sampler0, texCoords) * g_Color0;
	Out = sample;
	
	#if LAYER1 != 0
		texCoords = mul(In.Tex, (float2x2)g_TexTransform1) + g_TexTransform1._41_42;
		sample = tex2D(Sampler1, texCoords) * g_Color1;
		#if LAYER1 == 1
			Out += sample * sample.a;
		#elif LAYER1 == 2
			Out = lerp(Out, sample, sample.a);
		#endif
	#endif
	#if LAYER2 != 0
		texCoords = mul(In.Tex, (float2x2)g_TexTransform2) + g_TexTransform2._41_42;
		sample = tex2D(Sampler2, texCoords) * g_Color2;
		#if LAYER2 == 1
			Out += sample * sample.a;
		#elif LAYER2 == 2
			Out = lerp(Out, sample, sample.a);
		#endif
	#endif
	#if LAYER3 != 0
		texCoords = mul(In.Tex, (float2x2)g_TexTransform3) + g_TexTransform3._41_42;
		sample = tex2D(Sampler3, texCoords) * g_Color3;
		#if LAYER3 == 1
			Out += sample * sample.a;
		#elif LAYER3 == 2
			Out = lerp(Out, sample, sample.a);
		#endif
	#endif

	float fogParam = abs(In.Tex.y*2-1);
	float fog = saturate(fogParam * g_FogParams.x + g_FogParams.y);
	Out = lerp(Out, g_FogColor, fog);
}

technique {
	pass {
		VertexShader = compile vs_3_0 VS();
		PixelShader  = compile ps_3_0 PS();
	}
}

